<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jsp/taglib.jsp" %>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>确认结业</title>

    <!-- Bootstrap -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/Transfer.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <script type="text/javascript" src="/js/web3.min.js"></script>
    <script type="text/javascript" src="/js/bignumber.js"></script>

    <script src="/js/jquery-2.2.3.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script src="/js/Transfer.js" type="text/javascript"></script>
    <script type="text/javascript">
        /**
         * 准备信息
         */
        $(function () {
            alert("在进行转账操作之前，请在geth客户端下使用以下命令解锁账户。\n\n personal.unlockAccount('yourAddress')");

            // 初始化web3对象
            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider);
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
            }

            var EDUContract = web3.eth.contract([{
                "constant": false,
                "inputs": [{"name": "receiver", "type": "address"}, {"name": "amount", "type": "uint256"}],
                "name": "sendCoin",
                "outputs": [{"name": "sufficient", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "addr", "type": "address"}],
                "name": "getBalance",
                "outputs": [{"name": "", "type": "uint256"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "inputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "constructor"
            }, {
                "anonymous": false,
                "inputs": [{"indexed": true, "name": "_from", "type": "address"}, {
                    "indexed": true,
                    "name": "_to",
                    "type": "address"
                }, {"indexed": false, "name": "_value", "type": "uint256"}],
                "name": "Transfer",
                "type": "event"
            }]);
            var EDU = EDUContract.at("0xf6a2a78eb90df4726f3f0f56cb1b08517df0211a");

            var account = '${address}';
            console.log(account);
            var etherBalance = web3.fromWei(web3.eth.getBalance(account).toNumber(), 'ether');
            var eduBalance = EDU.getBalance.call(account);

            document.getElementById("etherBalance").innerText = "Ether 余额： " + etherBalance;
            document.getElementById("eduBalance").innerText = "EDU 余额： " + eduBalance;
        });

        /**
         * 发送交易
         */
        function sendTransaction() {
            /*
             MetaCoin代币部分
             1. 取到MetaCoin合约对象
             2. metacoin就是获取到的合约对象实例，此时metacoin对象中就包含了与合约函数同名的Javascript函数，之后就可以通过metacoin对象来调用合约中的函数
             */
            var EDUContract = web3.eth.contract([{
                "constant": true,
                "inputs": [],
                "name": "name",
                "outputs": [{"name": "", "type": "string"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}],
                "name": "approve",
                "outputs": [{"name": "success", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": true,
                "inputs": [],
                "name": "totalSupply",
                "outputs": [{"name": "", "type": "uint256"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_from", "type": "address"}, {"name": "_to", "type": "address"}, {
                    "name": "_value",
                    "type": "uint256"
                }],
                "name": "transferFrom",
                "outputs": [{"name": "success", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": true,
                "inputs": [],
                "name": "decimals",
                "outputs": [{"name": "", "type": "uint8"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_value", "type": "uint256"}],
                "name": "burn",
                "outputs": [{"name": "success", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": true,
                "inputs": [{"name": "", "type": "address"}],
                "name": "balanceOf",
                "outputs": [{"name": "", "type": "uint256"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_from", "type": "address"}, {"name": "_value", "type": "uint256"}],
                "name": "burnFrom",
                "outputs": [{"name": "success", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": true,
                "inputs": [],
                "name": "symbol",
                "outputs": [{"name": "", "type": "string"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}],
                "name": "transfer",
                "outputs": [],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "_spender", "type": "address"}, {
                    "name": "_value",
                    "type": "uint256"
                }, {"name": "_extraData", "type": "bytes"}],
                "name": "approveAndCall",
                "outputs": [{"name": "success", "type": "bool"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "constant": true,
                "inputs": [{"name": "", "type": "address"}, {"name": "", "type": "address"}],
                "name": "allowance",
                "outputs": [{"name": "", "type": "uint256"}],
                "payable": false,
                "stateMutability": "view",
                "type": "function"
            }, {
                "constant": false,
                "inputs": [{"name": "addr", "type": "address"}],
                "name": "getBalance",
                "outputs": [{"name": "", "type": "uint256"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "function"
            }, {
                "inputs": [{"name": "initialSupply", "type": "uint256"}, {
                    "name": "tokenName",
                    "type": "string"
                }, {"name": "decimalUnits", "type": "uint8"}, {"name": "tokenSymbol", "type": "string"}],
                "payable": false,
                "stateMutability": "nonpayable",
                "type": "constructor"
            }, {
                "anonymous": false,
                "inputs": [{"indexed": true, "name": "from", "type": "address"}, {
                    "indexed": true,
                    "name": "to",
                    "type": "address"
                }, {"indexed": false, "name": "value", "type": "uint256"}],
                "name": "Transfer",
                "type": "event"
            }, {
                "anonymous": false,
                "inputs": [{"indexed": true, "name": "from", "type": "address"}, {
                    "indexed": false,
                    "name": "value",
                    "type": "uint256"
                }],
                "name": "Burn",
                "type": "event"
            }]);
            var EDU = EDUContract.at("0xb9300944b96cb7f8551755affdd6cb2ba0d318a9");


            // 获取交易基本信息
            var coinType = $("#coinType").val();
            var fromAddress = '${address}';
            var etherBalance = web3.eth.getBalance(fromAddress).toNumber();
            var eduBalance = EDU.getBalance.call(fromAddress);
            var toAddress = $("#account_to").val();
            var money;

            console.log(fromAddress + " " + toAddress + " " + etherBalance + " " + eduBalance + " " + money + " " + coinType);

            if (!web3.isAddress(toAddress)) {
                alert("请指定合法接收人！");
            } else if ($("#amount-number").val() == "") {
                alert("请指定发送数量！");
            } else {
                if (coinType == "Ether") {
                    money = web3.toWei($("#amount-number").val(), 'ether');
                    if (money >= etherBalance) {
                        alert("该账户资金不足！");
                    } else {
                        var fileInfo = getFileInfo();
                        var md5 = strToHexUnicodeStr(fileInfo.filehash);
                        var transaction = {
                            from: fromAddress,
                            to: toAddress,
                            value: money,
                            data: md5
                        };

                        web3.eth.sendTransaction(transaction, function (err) {
                            if (!err) {
                                $.ajax({
                                    url: "<spring:url value='/certification/certify' />",
                                    method: "post",
                                    data:{
                                        fileHash: fileInfo.fileHash,
                                        fileName:fileInfo.fileName,
                                        userId: "abcdefghigklmnopqrst",
                                        courseId: 12345
                                    },
                                    success: function (data) {
                                        alert(data);
                                        alert("认证成功！");
                                    }
                                });
                            } else {
                                alert("交易失败！\n\n未解锁账户或者账户资金不足！");
                            }
                        });
                    }
                } else {
                    money = $("#amount-number").val();
                    if (money >= eduBalance) {
                        alert("该账户资金不足！");
                    } else {
                        var txHash = EDU.transfer.sendTransaction(toAddress, money, {from: fromAddress}, function (err) {
                            if (!err) {
                                alert("交易成功！请在geth下使用 miner.start() 操作同步区块。\n挖矿结束后，使用 miner.stop() 结束挖矿！");
                            } else {
                                alert("交易失败！请解锁账户或者减少交易金额！");
                            }
                        });
                    }
                }
            }
        }


        function getFileInfo() {
            var formData = new FormData($("#fileForm")[0]);
            if($("#file").val() == "") {
                alert("请选择结业认证文件!");
            }else{
                var result = "";
                $.ajax({
                    url: "<spring:url value='/certification/check'/>",
                    type: "POST",
                    data: formData,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        result = data;
                    }
                });
                return result;
            }
        }

        /**
         * 字符串传16进制unicode编码
         */
        function strToHexUnicodeStr(str) {
            if (str === "")
                return "";
            var resultStr = "";
            for (var i = 0; i < str.length; i++) {

                var tempStr = parseInt(str[i].charCodeAt(0), 10).toString(16);

                if (tempStr.length < 4) {
                    var diff = 4 - tempStr.length;
                    for (var j = 0; j < diff; j++) {
                        tempStr = "0" + tempStr;
                    }
                }
                resultStr += tempStr;
            }
            return "0x" + resultStr;
        }

        /**
         * 16进制转字符串
         * @param hexCharCode
         * @returns {*}
         */
        function hexCharCodeToStr(hexCharCode) {
            // trim()方法会从一个字符串的两端删除空白字符
            var trimedStr = hexCharCode.trim();
            var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;

            var len = rawStr.length;
            if (len % 4 !== 0) {
                alert("Illegal Format Code!");
                return "";
            }

            var curCharCode;
            var resultStr = [];
            for (var i = 0; i < len; i = i + 4) {
                curCharCode = parseInt(rawStr.substr(i, 4), 16);
                resultStr.push(String.fromCharCode(curCharCode));
            }
            return resultStr.join("");
        }
    </script>
</head>
<body>

<div class="head">
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed brand" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="<spring:url value="/" />" style="color: #ffffff">
                    <img src="<spring:url value="/images/logo/logo_blue.png" />"/>
                </a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    <li class="dropdown loginMenu">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                           aria-expanded="false">个人中心<span class="glyphicon glyphicon-menu-down"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="<spring:url value='/personalCenter/index' />">个人中心</a></li>
                            <li><a href="<spring:url value='/wallet/index' />">优得钱包</a></li>
                            <li><a href="<spring:url value='/logout' />">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</div>
<div class="container-wrap transfer-body">
    <div class="container">
        <div class="row transfer-container">
            <div class="col-md-11 transfer-head">结业认证文件颁布及奖励金</div>
            <div class="col-md-11 transfer-divider"></div>

            <div class="col-md-9 transfer-amount">
                <div class="transfer-label transfer-h1">选择认证文件</div>
                <form id="fileForm" enctype="multipart/form-data">
                    <input type="file" name="file" id="file">
                </form>
            </div>

            <div class="col-md-8 transfer-from">
                <div class="transfer-label transfer-h1">我的账户</div>
                <div class="transfer-account">
                    <div class="account-number">测试账户地址</div>
                    <div class="transfer-remainder" id="etherBalance"></div>
                    <div class="transfer-remainder" id="eduBalance"></div>
                </div>
            </div>
            <div class="col-md-3 transfer-info">
                <span class="from-info">
                    <img class="img-circle from-portrait" src="/images/wallet/wallet-portrait.png">
                    <span class="wallet-h1 from-username">测试账户用户名</span>
                </span>
            </div>
            <div class="col-md-11 transfer-mid">
                <img class="transfer-icon" src="/images/wallet/transfer.png">
                <span class="transfer-h1">转账到</span>
            </div>
            <div class="col-md-8 transfer-to">
                <label class="transfer-label transfer-h1" for="account_to">对方账户</label>
                <input class="transfer-account account-number" placeholder="0x0000000000000000000..."
                       required="required" type="text" id="account_to"/>
            </div>
            <div class="col-md-11 transfer-amount">
                <form role="form" action method="post" class="login-form" id="login-form">
                    <label for="amount-number" class="amount-label transfer-h1">转账金额</label>
                    <input type="text" name="amount-number" class="amount-input" id="amount-number" required="required">
                    <span class="amount-conversion">
                            <select class="amount-input" id="coinType">
                                <option value="Ether">Ether</option>
                                <option value="EDU">EDU</option>
                            </select>
                        </span>
                    <input type="button" value="确认结业" class="transfer-define" onclick="sendTransaction()">
                </form>
            </div>
        </div>
    </div>
</div>
<br>
</body>
</html>